#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <openssl/sha.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

#define PORT 8080
#define BUFFER_SIZE 1024

// 函数声明
void handle_client(int client_socket);
int main() {
    // 创建套接字
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
    
    // 在macOS上SO_REUSEPORT可能导致Protocol not available错误
    // 分开设置SO_REUSEADDR和SO_REUSEPORT以提高兼容性
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt SO_REUSEADDR");
        exit(EXIT_FAILURE);
    }
    
    // 尝试设置SO_REUSEPORT，但不强制要求成功
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)) < 0) {
        perror("setsockopt SO_REUSEPORT (ignored)");
        // 忽略错误，继续执行
    }
    
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
    
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    
    printf("服务器启动，监听端口 %d\n", PORT);
    
    time_t last_check = time(NULL);
    
    while(1) {
        // 非阻塞接受客户端连接
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(server_fd, &readfds);
        
        struct timeval timeout;
        timeout.tv_sec = 1;  // 1秒超时
        timeout.tv_usec = 0;
        
        int activity = select(server_fd + 1, &readfds, NULL, NULL, &timeout);
        
        if (activity > 0 && FD_ISSET(server_fd, &readfds)) {
            if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
                perror("accept");
                exit(EXIT_FAILURE);
            }
            
            handle_client(new_socket);
        }
    }
    
    return 0;
}

void handle_client(int client_socket) {
    char buffer[BUFFER_SIZE] = {0};
    int valread = read(client_socket, buffer, BUFFER_SIZE);
    
    // 简单的命令解析
    if (strncmp(buffer, "REGISTER", 8) == 0) {
        // 注册逻辑
        send(client_socket, "注册成功", 8, 0);
    } else if (strncmp(buffer, "LOGIN", 5) == 0) {
        // 登录逻辑
        send(client_socket, "登录成功", 8, 0);
    } else {
        send(client_socket, "无效命令", 8, 0);
    }
    
    close(client_socket);
}